﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using SoftwareConsulting.BI11.Studio.InternalServices;

namespace SoftwareConsulting.BI11.Controls
{
    /// <summary>
    /// Класс диалога поиска ситуации
    /// </summary>
    internal partial class CustomizedDataGridChooseColumnsDialog : RestorableForm
    {
        private CustomizedDataGrid _grid; //настраиваемый датагрид        

        public CustomizedDataGridChooseColumnsDialog(CustomizedDataGrid grid)
        {
            _grid = grid;
            InitializeComponent();
        }        

        /// <summary>
        /// Инициализация диалога
        /// </summary>
        private void Initialize()
        {
            var columns = _grid.Columns;
            var column = columns.GetFirstColumn(DataGridViewElementStates.None);            
            var items = VisibleColumnsBox.Items;
            items.Clear();
            while (column != null)
            {                
                var item = items.Add(column.HeaderText);
                item.Tag = column;
                item.Checked = column.Visible;
                if (column.Frozen)
                    item.ForeColor = System.Drawing.SystemColors.GrayText;
                column = columns.GetNextColumn(column, DataGridViewElementStates.None, DataGridViewElementStates.None);
            }
        }

        /// <summary>
        /// Возвращает флаг "замороженного" столбца
        /// </summary>
        /// <param name="columnsBoxIndex"></param>
        /// <returns></returns>
        private bool IsFrozenColumn(int columnsBoxIndex)
        {
            return (VisibleColumnsBox.Items[columnsBoxIndex].Tag as DataGridViewColumn).Frozen;
        }

        /// <summary>
        /// Обрабатывает смену выделения в списке отображаемых столбцов
        /// </summary>
        private void ProcessSelectionChange()
        {
            foreach (int index in VisibleColumnsBox.SelectedIndices)
            {
                bool isFrozen = IsFrozenColumn(index);
                UpButton.Enabled = !isFrozen && (index > 0) && !IsFrozenColumn(index - 1);
                DownButton.Enabled = !isFrozen && (index < (VisibleColumnsBox.Items.Count - 1)) && !IsFrozenColumn(index + 1);
                return;
            }            
        }

        /// <summary>
        /// Сдвигает выделенный столбец в указанном направлении
        /// </summary>
        /// <param name="direction"></param>
        private void MoveColumn(Directions1D direction)
        {            
            foreach (ListViewItem item in VisibleColumnsBox.SelectedItems)
            {                
                int index = item.Index + (direction == Directions1D.Back ? -1 : 1);
                var column = item.Tag as DataGridViewColumn;
                string columnHeader = item.Text;
                var items = VisibleColumnsBox.Items;                
                items.Remove(item);
                var newItem = items.Insert(index, columnHeader);
                newItem.Tag = column;
                newItem.Checked = column.Visible;
                VisibleColumnsBox.Focus();
                newItem.Focused = true;
                newItem.Selected = true;                
                VisibleColumnsBox.FocusedItem = newItem;                
                return;
            }
        }

        /// <summary>
        /// Применяет изменения и закрывает диалог
        /// </summary>
        private void ApplyAndClose()
        {
            var columns = _grid.Columns;            
            var items = VisibleColumnsBox.Items;            
            for (int i = 0; i < items.Count; i++)
            {
                var item = items[i];
                var column = item.Tag as DataGridViewColumn;
                column.DisplayIndex = i;
                column.Visible = item.Checked;
            }
            DialogResult = DialogResult.OK;
            Close();
        }

        private void CustomizedDataGridChooseColumnsDialog_Load(object sender, EventArgs e)
        {
            Initialize();
        }

        private void VisibleColumnsBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ProcessSelectionChange();
        }

        private void UpButton_Click(object sender, EventArgs e)
        {
            MoveColumn(Directions1D.Back);
        }

        private void DownButton_Click(object sender, EventArgs e)
        {
            MoveColumn(Directions1D.Forward);
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            ApplyAndClose();
        }
    }
}
